//
//  DR_FolderTopView.swift
//  DocReaderRP
//
//  Created by  mac on 2025/11/10.
//

import UIKit
import SnapKit

class DR_FolderTopView: UIView {

    var onFilterSelected: ((Int) -> Void)?
    var searchBlock: (() -> Void)?
    var filterBlock: (() -> Void)?
    var favoriteBlock: (() -> Void)?
    
    private var selectedIndex: Int = 0 {
        didSet {
            filterCollectionView.reloadData()
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        addSubview(bgView)
        bgView.addSubview(searchButton)
        bgView.addSubview(collectBtn)
        bgView.addSubview(filterCollectionView)
        addSubview(allLabel)
        addSubview(filterBtn)
        addSubview(checkImg)
        
        bgView.snp.makeConstraints { make in
            make.leading.trailing.top.equalToSuperview()
            make.bottom.equalTo(self.safeAreaLayoutGuide.snp.top).offset(115)
        }
        
        searchButton.snp.makeConstraints { make in
            make.leading.equalToSuperview().offset(15)
            make.trailing.equalTo(collectBtn.snp.leading).offset(-12)
            make.top.equalTo(self.safeAreaLayoutGuide).offset(16)
            make.height.equalTo(44)
        }
        
        collectBtn.snp.makeConstraints { make in
            make.trailing.equalToSuperview().offset(-15)
            make.top.equalTo(self.safeAreaLayoutGuide).offset(16)
            make.width.height.equalTo(44)
        }

        filterCollectionView.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview().inset(15)
            make.bottom.equalToSuperview()
            make.height.equalTo(36)
        }
        
        allLabel.snp.makeConstraints { make in
            make.leading.equalToSuperview().offset(15)
            make.top.equalTo(bgView.snp.bottom).offset(13.5)
            make.height.equalTo(21)
        }
        
        checkImg.snp.makeConstraints { make in
            make.trailing.equalToSuperview().offset(-15)
            make.centerY.equalTo(allLabel)
            make.height.width.equalTo(24)
        }
        
        filterBtn.snp.makeConstraints { make in
            make.trailing.equalTo(checkImg.snp.leading).offset(-20)
            make.centerY.equalTo(allLabel)
            make.height.width.equalTo(24)
        }
    }
    
    @objc private func clickSearchButton(){
        searchBlock?()
    }
    
    @objc private func clickFilterButton(){
        filterBlock?()
    }
    
    @objc private func clickFavoriteButton(){
        favoriteBlock?()
    }
    
    private let bgView: UIImageView = {
        let v = UIImageView()
        v.image = "folder_pdfBg".toImage
        v.contentMode = .scaleAspectFill
        v.isUserInteractionEnabled = true // 允许交互，让子视图可以接收触摸事件
        return v
    }()
    private lazy var searchButton: UIButton = {
        let button = UIButton(type: .custom)
        button.backgroundColor = .white
        button.layer.cornerRadius = 16
        button.addTarget(self, action: #selector(clickSearchButton), for: .touchUpInside)
        // 创建图标
        let iconImageView = UIImageView()
        iconImageView.image = "folder-search".toImage
        iconImageView.contentMode = .scaleAspectFill
        
        // 创建占位文本
        let placeholderLabel = UILabel()
        placeholderLabel.text = "search_title".localized
        placeholderLabel.textColor = "#7F8093".toColor
        placeholderLabel.font = UIFont.systemFont(ofSize: 15)
        
        // 创建容器视图
        button.addSubview(iconImageView)
        button.addSubview(placeholderLabel)

        // 设置约束
        iconImageView.snp.makeConstraints { make in
            make.leading.equalToSuperview().offset(12)
            make.centerY.equalToSuperview()
            make.width.height.equalTo(24)
        }
        
        placeholderLabel.snp.makeConstraints { make in
            make.leading.equalTo(iconImageView.snp.trailing).offset(8)
            make.centerY.equalToSuperview()
            make.trailing.lessThanOrEqualToSuperview()
        }
        
        return button
    }()
    
    private let collectBtn: UIButton = {
        let v = UIButton(type: .custom)
        v.setImage("folder_collect".toImage, for: .normal)
        v.addTarget(self, action: #selector(clickFavoriteButton), for: .touchUpInside)
        return v
    }()

    private lazy var filterCollectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.backgroundColor = .clear
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.isUserInteractionEnabled = true // 确保可以交互
        collectionView.allowsSelection = true // 确保允许选择
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(DR_FolderFilterCell.self, forCellWithReuseIdentifier: DR_FolderFilterCell.identifier)
        return collectionView
    }()
    
    private let allLabel: UILabel = {
        let v = UILabel()
        v.text = "search_all".localized
        v.textColor = .black
        v.font = UIFont.systemFont(ofSize: 18, weight: .medium)
        return v
    }()
    
    private let checkImg: UIImageView = {
        let v = UIImageView()
        v.image = "home_recent".toImage
        v.contentMode = .scaleAspectFill
        return v
    }()
    
    private let filterBtn: UIButton = {
        let v = UIButton(type: .custom)
        v.setImage("folder_filter".toImage, for: .normal)
        v.addTarget(self, action: #selector(clickFilterButton), for: .touchUpInside)
        return v
    }()
    
    private let filterItems = ["PDF", "Word", "Excel", "PPT"]
    
    override func layoutSubviews() {
        super.layoutSubviews()
        // 当布局更新时，刷新 CollectionView 的布局
        filterCollectionView.collectionViewLayout.invalidateLayout()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

// MARK: - UICollectionViewDataSource, UICollectionViewDelegate
extension DR_FolderTopView: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return filterItems.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: DR_FolderFilterCell.identifier, for: indexPath) as! DR_FolderFilterCell
        let model = DR_FolderFilterModel(title: filterItems[indexPath.item], isSelected: indexPath.item == selectedIndex)
        cell.configure(with: model)
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        if indexPath.item == 0 {
            bgView.image = "folder_pdfBg".toImage
        }else if indexPath.item == 1 {
            bgView.image = "folder_wordBg".toImage
        }else if indexPath.item == 2 {
            bgView.image = "folder_excelBg".toImage
        }else if indexPath.item == 3 {
            bgView.image = "folder_pptBg".toImage
        }
        selectedIndex = indexPath.item
        onFilterSelected?(indexPath.item)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        // 平均分配宽度
        let totalWidth = collectionView.bounds.width > 0 ? collectionView.bounds.width : UIScreen.main.bounds.width - 30
        let width = totalWidth / CGFloat(filterItems.count)
        return CGSize(width: width, height: 36)
    }
}
